package com.zx.tv.ui;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Toast;

import com.zx.base.ctrl.Constant;
import com.zx.base.ctrl.KeyTable;
import com.zx.base.http.HttpUtils;
import com.zx.base.http.URLHelper;
import com.zx.base.lazylist.ImageLoader;
import com.zx.base.util.DPIExchange;
import com.zx.tv.MusicReceiver;
import com.zx.tv.R;
import com.zx.tv.app.NewTVApp;

public class Main extends Activity {

	private ImageView main_pic_1, main_pic_2, main_pic_3, main_pic_4,
			main_pic_5;
	private RelativeLayout top, bottom, substance;
	private LinearLayout header;
	private ImageLoader imageloader;
	private int mClick = 0;
	private Button top_button0, top_button1, top_button2, top_button3,
			top_button4, top_button5;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		imageloader = ((NewTVApp) getApplication()).imageloader;
		setContentView(R.layout.main);

		top_button0 = (Button) findViewById(R.id.top_button0);
		top_button0.setOnClickListener(listener);
		top_button1 = (Button) findViewById(R.id.top_button1);
		top_button1.setOnClickListener(listener);
		top_button2 = (Button) findViewById(R.id.top_button2);
		top_button2.setOnClickListener(listener);
		top_button3 = (Button) findViewById(R.id.top_button3);
		top_button3.setOnClickListener(listener);
		top_button4 = (Button) findViewById(R.id.top_button4);
		top_button4.setOnClickListener(listener);
		top_button5 = (Button) findViewById(R.id.top_button5);
		top_button5.setOnClickListener(listener);
		
		top_button0.setTextColor(Color.YELLOW);
		top_button0.setBackgroundResource(R.drawable.nav_bg);

		top = (RelativeLayout) findViewById(R.id.top);
		bottom = (RelativeLayout) findViewById(R.id.bottom);
		substance = (RelativeLayout) findViewById(R.id.substance);
		header = (LinearLayout) findViewById(R.id.header);
		DPIExchange dpi = new DPIExchange(this);
		LayoutParams toplp = new LayoutParams(LayoutParams.MATCH_PARENT,
				dpi.heightChange(100));
		top.setLayoutParams(toplp);
		LayoutParams headerlp = new LayoutParams(LayoutParams.MATCH_PARENT,
				dpi.heightChange(100));
		headerlp.setMargins(dpi.widthChange(375), 0, dpi.widthChange(375), 0);
		header.setLayoutParams(headerlp);
		LayoutParams bottomlp = new LayoutParams(LayoutParams.MATCH_PARENT,
				dpi.heightChange(100));
		bottomlp.alignWithParent = true;
		bottomlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		bottom.setLayoutParams(bottomlp);
		LayoutParams rp = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		rp.setMargins(dpi.widthChange(375), dpi.heightChange(200),
				dpi.widthChange(375), dpi.heightChange(200));
		substance.setLayoutParams(rp);
		main_pic_1 = (ImageView) findViewById(R.id.main_pic_1);
		main_pic_2 = (ImageView) findViewById(R.id.main_pic_2);
		main_pic_3 = (ImageView) findViewById(R.id.main_pic_3);
		main_pic_4 = (ImageView) findViewById(R.id.main_pic_4);
		main_pic_5 = (ImageView) findViewById(R.id.main_pic_5);


		new InfoTask().execute(URLHelper.mPrefix);
	}

	class InfoTask extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {

			Map<String, String> map = new HashMap<String, String>();
			map.put("act", "indexPicList");
			return HttpUtils.readHttp(params[0], map);// 网络操作，向服务器发送登录请求，获取返回信息

		}

		@Override
		protected void onPostExecute(String result) {

			if (Constant.debug)
				Log.d("TAG", "login result = " + result);
			if (result == null || result.equals("timeout") || result == "") {
				Toast toast = Toast.makeText(Main.this, "网络超时。",
						Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();

			} else {
				// 发送解析数据 消息
				parseJson(result);
			}

		}

		// 解析获取的服务器json数据
		private void parseJson(String str) {
			try {
				JSONObject result = new JSONObject(str);
				String succeed = result.getString("succeed");
				if (succeed.equals("000")) {
					JSONArray datalist = result.getJSONArray("dataList");
					for (int i = 0; i < datalist.length(); i++) {
						JSONObject one = datalist.getJSONObject(i);
						//final String oneid = one.getString("type");
						switch (one.getInt("sequence")) {
						case 1:
							imageloader.DisplayImage(
									URLHelper.mPrefixImg
											+ one.getString("imgurl"),
									main_pic_1, R.drawable.loading);
							
							break;
						case 2:
							imageloader.DisplayImage(
									URLHelper.mPrefixImg
											+ one.getString("imgurl"),
									main_pic_2, R.drawable.loading);

							break;
						case 3:
							imageloader.DisplayImage(
									URLHelper.mPrefixImg
											+ one.getString("imgurl"),
									main_pic_3, R.drawable.loading);

							break;
						case 4:
							imageloader.DisplayImage(
									URLHelper.mPrefixImg
											+ one.getString("imgurl"),
									main_pic_4, R.drawable.loading);

							break;
						case 5:
							imageloader.DisplayImage(
									URLHelper.mPrefixImg
											+ one.getString("imgurl"),
									main_pic_5, R.drawable.loading);
							break;
						default:
							break;
						}

					}

				} else {

				}
			} catch (Exception e) {
				
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			Dialog dialog = buildDialog1(Main.this);
			dialog.setCanceledOnTouchOutside(false);
			dialog.show();

			return true;
		} else if (keyCode == KeyTable.KEY_LEFT
				|| keyCode == KeyTable.KEY_ENTER) {
			if (keyCode == KeyTable.KEY_ENTER) {
				Intent intent = new Intent(Main.this, NewList.class);
				intent.putExtra("listId", mClick + 1);
				startActivity(intent);
			}
			mClick--;
			if (mClick == -1) {
				mClick = 0;
			}

			switch (mClick) {
			case 0:
				top_button0.setTextColor(Color.YELLOW);
				top_button0.setBackgroundResource(R.drawable.nav_bg);
				top_button1.setTextColor(Color.BLACK);
				top_button1.setBackgroundResource(R.drawable.nothing);
				main_pic_1.setAlpha(255);
				main_pic_2.setAlpha(255);
				main_pic_3.setAlpha(255);
				main_pic_4.setAlpha(255);
				main_pic_5.setAlpha(255);
				
				break;
			case 1:
				top_button1.setTextColor(Color.YELLOW);
				top_button1.setBackgroundResource(R.drawable.nav_bg);
				top_button2.setTextColor(Color.BLACK);
				top_button2.setBackgroundResource(R.drawable.nothing);
				main_pic_1.setAlpha(255);
				main_pic_2.setAlpha(150);
				break;
			case 2:
				top_button2.setTextColor(Color.YELLOW);
				top_button2.setBackgroundResource(R.drawable.nav_bg);
				top_button3.setTextColor(Color.BLACK);
				top_button3.setBackgroundResource(R.drawable.nothing);
				main_pic_2.setAlpha(255);
				main_pic_3.setAlpha(150);
				break;
			case 3:
				top_button3.setTextColor(Color.YELLOW);
				top_button3.setBackgroundResource(R.drawable.nav_bg);
				top_button4.setTextColor(Color.BLACK);
				top_button4.setBackgroundResource(R.drawable.nothing);
				main_pic_3.setAlpha(255);
				main_pic_4.setAlpha(150);
				break;
			case 4:
				top_button4.setTextColor(Color.YELLOW);
				top_button4.setBackgroundResource(R.drawable.nav_bg);
				top_button5.setTextColor(Color.BLACK);
				top_button5.setBackgroundResource(R.drawable.nothing);
				main_pic_4.setAlpha(255);
				main_pic_5.setAlpha(150);
				break;
			case 5:
				
				break;
			}
		} else if (keyCode == KeyTable.KEY_RIGHT
				|| keyCode == KeyTable.KEY_ENTER) {
			if (keyCode == KeyTable.KEY_ENTER) {
				Intent intent = new Intent(Main.this, NewList.class);
				intent.putExtra("listId", mClick + 1);
				startActivity(intent);
			}
			mClick++;
			if (mClick == 6) {
				mClick = 5;
			}
			switch (mClick) {
			case 0:
				break;
			case 1:
				top_button1.setTextColor(Color.YELLOW);
				top_button1.setBackgroundResource(R.drawable.nav_bg);
				top_button0.setTextColor(Color.BLACK);
				top_button0.setBackgroundResource(R.drawable.nothing);
				main_pic_1.setAlpha(150);
				main_pic_2.setAlpha(150);
				main_pic_3.setAlpha(150);
				main_pic_4.setAlpha(150);
				main_pic_5.setAlpha(150);
				main_pic_1.setAlpha(255);
				break;
			case 2:
				top_button2.setTextColor(Color.YELLOW);
				top_button2.setBackgroundResource(R.drawable.nav_bg);
				top_button1.setTextColor(Color.BLACK);
				top_button1.setBackgroundResource(R.drawable.nothing);
				main_pic_1.setAlpha(150);
				main_pic_2.setAlpha(255);
				break;
			case 3:
				top_button3.setTextColor(Color.YELLOW);
				top_button3.setBackgroundResource(R.drawable.nav_bg);
				top_button2.setTextColor(Color.BLACK);
				top_button2.setBackgroundResource(R.drawable.nothing);
				main_pic_2.setAlpha(150);
				main_pic_3.setAlpha(255);
				break;
			case 4:
				top_button4.setTextColor(Color.YELLOW);
				top_button4.setBackgroundResource(R.drawable.nav_bg);
				top_button3.setTextColor(Color.BLACK);
				top_button3.setBackgroundResource(R.drawable.nothing);
				main_pic_3.setAlpha(150);
				main_pic_4.setAlpha(255);
				break;
			case 5:
				top_button5.setTextColor(Color.YELLOW);
				top_button5.setBackgroundResource(R.drawable.nav_bg);
				top_button4.setTextColor(Color.BLACK);
				top_button4.setBackgroundResource(R.drawable.nothing);
				main_pic_4.setAlpha(150);
				main_pic_5.setAlpha(255);
				break;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	private View.OnClickListener listener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			if (mClick != 0) {

				Intent intent = new Intent(Main.this, NewList.class);
				intent.putExtra("listId", mClick + "");
				startActivity(intent);

			}

		}
	};
	
	public Dialog buildDialog1(Context context) { 
		boolean bl = false;
		
        AlertDialog.Builder builder = new AlertDialog.Builder(context);   
        builder.setTitle("您确定想要退出？");   
        builder.setPositiveButton("确定",   
                new DialogInterface.OnClickListener() {   
                    public void onClick(DialogInterface dialog, int whichButton) {   
                    	dialog.dismiss();
                    	
                    	Intent intent = new Intent(Main.this, MusicReceiver.class);

            			Bundle bundle = new Bundle();
            			bundle.putInt("op", 4);
            			intent.putExtras(bundle);

            			sendBroadcast(intent);

            			String packName = Main.this.getPackageName();
            			ActivityManager activityMgr = (ActivityManager) Main.this
            					.getSystemService(Context.ACTIVITY_SERVICE);
            			activityMgr.restartPackage(packName);// 需要权限<uses-permission

            			activityMgr.killBackgroundProcesses(packName);// 需要权限
            															// <uses-permission

            			android.os.Process.killProcess(android.os.Process.myPid());
                    }   
                });   
        builder.setNegativeButton("取消",   
                new DialogInterface.OnClickListener() {   
                    public void onClick(DialogInterface dialog, int whichButton) {   

                    	dialog.dismiss();
                    }   
                });   
        return builder.create();   
  
    }

}